<?php
//订单商品表
class OrderGoods{

	function get_by_order_id($order_id){
	
		$mOrderGoods = M('OrderGoods');
		//返回自增id
		return $mOrderGoods->table('order_goods AS og')
		->join('goods AS g ON g.id = og.goods_id')
		->join('cate AS c ON c.id = g.cate_id')
		->join('images AS i ON i.id = g.image')
		->join('goods_attr AS ga ON ga.id = og.goods_attr')
		->where('og.order_id = '.$order_id)
		->field('og.*,
			g.name AS goods_name,
			g.ename,
			g.describe,
			g.unit,
			g.cate_id,
			og.goods_price * og.goods_number AS subtotal,
			i.original,
			i.thumb,
			ga.name AS attr_name,
			ga.title AS attr_title
		')
		->select();
	}
	
	function del_by_id($id){

		$mOrderGoods = M('OrderGoods');
		//返回自增id
		return $mOrderGoods->where('id = '.$id)->delete();
	}
	
	function get_by_id($id){

		$mOrderGoods = M('OrderGoods');
		//返回自增id
		return $mOrderGoods->where('id = '.$id)->find();
	}
	
	//获取订单中指定商品
	function get_by_goods_id($order_id,$goods_id,$goods_attr){
		$mOrderGoods = M('OrderGoods');
		//返回自增id
		return $mOrderGoods->where('order_id = '.$order_id.' AND goods_id = '.$goods_id.' AND goods_attr = '.$goods_attr)->find();
	}
	
	/**
	 * 修改
	 */
	function update($id,$upItems){
		$mOrderGoods = M('OrderGoods');
		return $mOrderGoods -> where('id='.$id)->save($upItems);
	}
	
	//订单添加商品
	function add($data){
		
		$data['created'] = full_date();
		
		$mOrderGoods = M('OrderGoods');
		return $mOrderGoods -> add($data);
	}
	
	//订单添加商品
	function addAll($goods){
		
		$mOrderGoods = M('OrderGoods');
		return $mOrderGoods -> addAll($goods);
	}
	
	/**
	 * 
	 * 惊喜小物排序
	 * @param unknown_type $goods
	 */
	function surpriseSort($goods){
	
		$canJu 		= C('GOODS_CANJU');		 	//餐具
		$laZhu 		= C('GOODS_LAZHU');			//蜡烛
		$heKa 		= C('GOODS_HEKA');			//贺卡
		$yanHuaBang = C('GOODS_YANHUABANG');	//烟花棒
		
		$sortGoods = array(
			$canJu => null,
			$laZhu => null,
			$heKa => null,
			$yanHuaBang => null
		);
		
		foreach ($goods as $i => $g){
			$sortGoods[$g['goods_id']] = $g;
		}
		
		return $sortGoods;
	}
	
	/**
	 * 
	 * 商品总金额
	 * @param unknown_type $goods
	 */
	function goods_sum_price($goods){
		
		$sum_price = 0;
		foreach ($goods as $i => $g){
			if($g){
				$sum_price += floatval($g['subtotal']);
			}
		}
		
		return $sum_price;
	}
	
	/**
	 * 
	 * 订单商品总金额
	 * @param unknown_type $order_id
	 */
	function order_goods_amount($order_id){
		
		$mOrderGoods = M('OrderGoods');
		//返回自增id
		return $mOrderGoods->table('order_goods')
		->where('order_id = '.$order_id)
		->getField('
			SUM(goods_price * goods_number) AS goods_amount
		');
	}
}